package config

import (
	"strings"

	"github.com/TarsCloud/TarsGo/tars/util/conf"
	"github.com/gogf/gf/v2/container/gmap"
	"github.com/wzh200x/hyperNexus/hyperNexusType"
)

// PlatformConfig 平台配置结构体
type PlatformConfig struct {
	Configs *gmap.StrAnyMap
}

// PlatformAppInfo 平台应用信息结构体
type PlatformAppInfo struct {
	AppID       string `json:"appId"`
	AppSecret   string `json:"appSecret"`
	PackageName string `json:"packageName"`
	PrivateKey  string `json:"privateKey"`
	PublicKey   string `json:"publicKey"`
}

// PlatformInfo 平台信息结构体
type PlatformInfo struct {
	Apps []*PlatformAppInfo `json:"apps"`
}

// GlobalPlatformConfig 全局平台配置
var GlobalPlatformConfig PlatformConfig

// InitPlatformConfig 初始化平台配置
func InitPlatformConfig(sConf *conf.Conf) {
	// 从配置文件中读取平台配置
	GlobalPlatformConfig = PlatformConfig{
		Configs: gmap.NewStrAnyMap(false),
	}
	for i := 1; i < hyperNexusType.PlatformTypeMax; i++ {
		platformName := hyperNexusType.GetPlatformName(i)
		if platformName != "Unknown" {
			// platform 转小写
			platformName = strings.ToLower(platformName)
			platformPath := "/server/platforms/" + platformName
			apps := sConf.GetDomain(platformPath)
			platformInfo := &PlatformInfo{
				Apps: make([]*PlatformAppInfo, 0, len(apps)),
			}
			for _, appName := range apps {
				appPath := platformPath + "/" + appName
				appInfo := &PlatformAppInfo{
					AppID:       GetStringWithDef(appPath+"/appId", "", sConf),
					AppSecret:   GetStringWithDef(appPath+"/appSecret", "", sConf),
					PackageName: GetStringWithDef(appPath+"/packageName", "", sConf),
					PrivateKey:  GetStringWithDef(appPath+"/privateKey", "", sConf),
					PublicKey:   GetStringWithDef(appPath+"/publicKey", "", sConf),
				}
				platformInfo.Apps = append(platformInfo.Apps, appInfo)
			}
			GlobalPlatformConfig.Configs.Set(platformName, platformInfo)
		}
	}
}

// GetStringWithDef 从配置文件中获取字符串，如果不存在则返回默认值
func GetStringWithDef(key string, defaultValue string, sConf *conf.Conf) string {
	value := ""
	value = sConf.GetStringWithDef(key, defaultValue)

	return value
}

// GetPlatformConfig 获取平台配置
func GetPlatformConfig(platformType int) *PlatformInfo {
	platform := hyperNexusType.GetPlatformName(platformType)
	// platform 转小写
	platform = strings.ToLower(platform)
	if GlobalPlatformConfig.Configs.Contains(platform) {
		return GlobalPlatformConfig.Configs.Get(platform).(*PlatformInfo)
	}
	return nil
}

// GetPlatformAppConfig 获取平台应用配置
func GetPlatformAppConfig(platformType int, appId string) *PlatformAppInfo {
	platformInfo := GetPlatformConfig(platformType)
	if platformInfo == nil {
		return nil
	}
	for _, appInfo := range platformInfo.Apps {
		if appInfo.AppID == appId {
			return appInfo
		}
	}
	return nil
}
